import { useEffect, useRef, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'
import { setCustomFrom, getCustomFrom } from '@/request/basicSettings'
import Generator from 'fr-generator';
import { message } from 'antd';

const CustomFrom = () => {
    const location = useLocation()
    const formRef: any = useRef(null)
    const [data, setData]: any = useState({})
    useEffect(() => {
        setData(location.state)
        getCustom(location.state.id)
    }, [])
    const onSave = async () => {
        const text = JSON.stringify(formRef.current?.getValue() || {})
        const res = await setCustomFrom({
            nid: data.nid,
            id: data.id,
            text: text
        })
        if (res.status === 200) {
            getCustom(data.id)
            message.info('修改成功')
        }
    }
    const getCustom = async (id: number | string) => {
        const res = await getCustomFrom({
            id: id
        })
        const text = JSON.parse(res.data[0].text || '{}')
        formRef.current?.setValue(text)
        setData(res.data[0])
    }
    return (
        <div style={{ height: '80vh' }}>
            <Generator ref={formRef} onSave={onSave} />
        </div>
    );
};

export default CustomFrom;